package com.wx.timertask;

import com.wx.model.User;
import com.wx.model.templatemessage.First;
import com.wx.model.templatemessage.Keyworld;
import com.wx.model.templatemessage.WxTemplateMessage;
import com.wx.repository.UserRepository;
import com.wx.service.Impl.WXServiceImpl;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.time.DayOfWeek;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * @author ：LiuShihao
 * @date ：Created in 2020/10/13 5:47 下午
 * @desc ：工资日提醒
 */
@Slf4j
@Component
public class PaydayReminderTask {
    public static Boolean isRun = false;
    /**
     *
     */
    public static final String  cron1="0 0 8 * * ? " ;
    public static final String  cron2="0 * * * * ? " ;

    @Autowired
    UserRepository repository;
    @Autowired
    WXServiceImpl wxService;
    @Scheduled(cron = cron1)
    public void dayReminderTaskp(){
        if (isRun){
            return;
        }
        log.info("------每日工资定时任务来了");
        isRun = true;
        send();
        isRun = false;
    }

    public void send(){
        String days = "";
        String redisToken = wxService.getRedisToken();
        String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=ACCESS_TOKEN";
        String access_token = url.replace("ACCESS_TOKEN", redisToken);
        List<User> users = repository.findUserByFlag();
        for (User user : users) {
            if (StringUtils.isEmpty(user.getOpenID())){
                continue;
            }
            if (StringUtils.isEmpty(user.getDowndate())){
                continue;
            }
            //发工资日期   15号
            int downdate = Integer.parseInt(user.getDowndate());
            LocalDateTime now = LocalDateTime.now();

            //当天是几号
            int today = Integer.parseInt(now.format(DateTimeFormatter.ofPattern("dd")));

            //下个月下一次发工资的日期
            LocalDateTime nextSalaryDay = LocalDateTime.now().plusMonths(1);


            //判断当天是否已经过了发工资的日期
            if(downdate<today){
                // 说明本月工资已经发过了  需要和下个月日期比较
                Duration between = Duration.between(now,LocalDateTime.of(nextSalaryDay.getYear(),
                        nextSalaryDay.getMonth(),downdate,0,0,0));
                long l = between.toDays();
                days = Long.toString(l);
            }else {
                //否则说明  发工资日期 大于 今天 本月工资还没有发
                Duration between = Duration.between(now,LocalDateTime.of(now.getYear(),
                        now.getMonth(),downdate,0,0,0));
                long l = between.toDays();
                days = Long.toString(l);
            }
            String yyyyMMdd = now.format(DateTimeFormatter.ofPattern("yyyy年MM月dd日"));
            DayOfWeek dayOfWeek = now.getDayOfWeek();
            String week = "";
            switch (dayOfWeek){
                case MONDAY:
                    week = "星期一";
                    break;
                case TUESDAY:
                    week = "星期二";
                    break;
                case WEDNESDAY:
                    week = "星期三";
                    break;
                case THURSDAY:
                    week = "星期四";
                    break;
                case FRIDAY:
                    week = "星期五";
                    break;
                case SUNDAY:
                    week = "星期六";
                    break;
                default:
                    week = "星期天";
                    break;
            }
            First first = new First(user.getName(),"#FF8040"); //橙色
            Keyworld keyworld0 = new Keyworld(yyyyMMdd+" "+week,"#173177");//蓝色
            Keyworld keyworld1 = new Keyworld(user.getMessage(),"#FF2D2D");//红色
            Keyworld keyworld2 = new Keyworld(days,"#FF2D2D"); //红色
            JSONObject first1 = JSONObject.fromObject(first);
            JSONObject keyword01 = JSONObject.fromObject(keyworld0);
            JSONObject keyword11 = JSONObject.fromObject(keyworld1);
            JSONObject keyword21 = JSONObject.fromObject(keyworld2);
            JSONObject templateData = new JSONObject();
            templateData.put("first",first1);
            templateData.put("keyword0",keyword01);
            templateData.put("keyword1",keyword11);
            templateData.put("keyword2",keyword21);
            WxTemplateMessage wxTemplateMessage = new WxTemplateMessage(user.getOpenID(), "hlHap2QQCf-0oddoe-NDmdP0o8-DU6KFzUBwOwVNods", null,null);
            JSONObject msgData = JSONObject.fromObject(wxTemplateMessage);
            msgData.put("data",templateData.toString());
            System.out.println(msgData);
            httpClient(access_token, "POST", msgData.toString());
        }
    }

    public String httpClient(String Url,String RequestMethod,String data){
        StringBuffer sb = null;
        try {
//            建立连接
            URL url = new URL(Url);
            HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection();
            httpUrlConn.setDoInput(true);
            httpUrlConn.setDoOutput(true);
            String s = RequestMethod.toUpperCase();
            httpUrlConn.setRequestMethod(s);
            httpUrlConn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
            if ("GET".equalsIgnoreCase(RequestMethod)){
                httpUrlConn.connect();
            }else {
                //设置请求头   //设置参数类型是json格式
                //httpUrlConn.connect();     可要    可不要
                BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(httpUrlConn.getOutputStream(), "UTF-8"));
                writer.write(data);
                writer.close();
                // 获取输入流

            }
            InputStream inputStream = httpUrlConn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

            // 读取返回结果
            sb = new StringBuffer();
            String str = null;
            while ((str = bufferedReader.readLine()) != null) {
                sb.append(str);
            }
            // 释放资源
            bufferedReader.close();
            inputStreamReader.close();
            inputStream.close();
            httpUrlConn.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(sb);
        return sb.toString();
    }

    public static void main(String[] args) {
        LocalDateTime now = LocalDateTime.now();
        int downdate = 15;
        int today = Integer.parseInt(now.format(DateTimeFormatter.ofPattern("dd")));
        LocalDateTime nextSalaryDay = LocalDateTime.now().plusMonths(1);
        String days = "";
        if(downdate<today){
            // 说明本月工资已经发过了  需要和下个月日期比较
            Duration between = Duration.between(now,LocalDateTime.of(nextSalaryDay.getYear(),
                    nextSalaryDay.getMonth(),downdate,0,0,0));
            long l = between.toDays();
            days = Long.toString(l);
        }else {
            //否则说明  发工资日期 大于 今天 本月工资还没有发
            Duration between = Duration.between(now,LocalDateTime.of(now.getYear(),
                    now.getMonth(),downdate,0,0,0));
            long l = between.toDays();
            days = Long.toString(l);
        }
        System.out.println(days);
    }
}
